<?php
namespace Home\Controller;
use Think\Controller;

class GoodsController extends Controller {

	/**
	 * [获取商品信息]
	 * @Author   Axing
	 * @DateTim 2017-07-26
	 * @return   [type]     [description]
	 */
	public function index() {
		// var_dump($_POST);die;
		$model = D('Goods');
		$pages = $this->page($_POST['pageNum'],$_POST['numPerPage']);

		//关键词判断
		if($_POST['keywords'] != '') {
			$keywords = " AND a.title LIKE '" . $_POST['keywords'] . "%'";
		} else {
			$keywords = '';
		}

		//日期区间判断
		if($_POST['star'] && $_POST['end']) {
			$time = " AND a.addtime BETWEEN '" . $_POST['star'] . "' AND '" . $_POST['end'] . "'";
		} else {
			$time = '';
		}

		//店铺id判断
		if($_POST['shop_name'] != '') {
			$shop_name = " AND b.name LIKE '" . $_POST['shop_name'] ."%'";
		} else {
			$shop_name = '';
		}

		//市场id判断
		if($_POST['city'] != '') {
			$city = " AND c.id = " . $_POST['city'];
		} else {
			$city = '';
		}

		//拼团id判断
		if($_POST['activity'] != '') {
			if($_POST['field'] == 'buygroup_id') {
				$buygroup = " AND a.istuangou = 1 AND a.buygroup_id = " . I("post.activity");
			} elseif($_POST['field'] == 'xihuan' || $_POST['field'] == 'tejia') {
				$buygroup = " AND a." . $_POST['field'] ." = 1";
			} else {
				$buygroup = " AND a." . $_POST['field'] ." = 2";
			}
		} else {
			$buygroup = '';
		}

		// var_dump($buygroup);die;

		//判断商品分类id
		if($_POST['categroy'] != '') {
			$categroy = " AND a.xilie = " . $_POST['categroy'];
		} else {
			$categroy = '';
		}

		//判断商品子分类id
		if($_POST['zifenlei'] != '') {
			$zifenlei = " AND a.zixilie = " . $_POST['zifenlei'];
		} else {
			$zifenlei = '';
		}

		if($_POST['keywords'] == '' && $_POST['star'] == '' && $_POST['shop_name'] == '' && $_POST['city'] == '' && $_POST['activity'] == '' && $_POST['categroy'] == '' && $_POST['zifenlei'] == '') {
			$tiaojian = " AND a.goodsid BETWEEN " . $pages['rtotal'] . " AND " . $pages['ltotal'];
			$limit = " LIMIT 0," . $pages['numPerPage'];
		} else {
			$tiaojian = '';
			// if($_POST['numPerPage'] == '') {
			// 	$_POST['numPerPage'] = 100;
			// }
			if($_POST['pageNum']) {
				$num = $_POST['pageNum'] * $pages['numPerPage']-$pages['numPerPage'];
			} else {
				$num = $_POST['pageNum'] * $pages['numPerPage'];
			}
			$limit = " LIMIT " . $num . "," . $pages['numPerPage'];
		}

 		
		$sql = "SELECT a.goodsid, a.check, a.addtime, a.xihuan, a.tejia, a.act_saohuo, a.act_xianshizhekou, a.act_nixiangyaode, a.title, a.istuangou, a.buygroup_id, a.images, a.price, a.xiaoliang, a.isnice, b.name AS shop_name, c.name AS city_name, d.name AS cate_name, e.name AS zi_name FROM goods AS a LEFT JOIN shop AS b ON b.shopid = a.shopid LEFT JOIN city AS c ON c.id = b.city LEFT JOIN categroy AS d ON d.cateid = a.xilie LEFT JOIN zifenlei AS e ON e.id = a.zixilie WHERE a.goodsid " . $keywords . $time . $shop_name . $city . $tiaojian . $buygroup . $categroy . $zifenlei . $limit;
		// echo $sql;
		// exit;
		$row = $model->query($sql);
		
		foreach($row as $key => $value) {
			$img = explode(',', $value['images']);
			$row[$key]['images'] = $img[0];
		}

		$row = $this->array_sort($row, 'goodsid', 'desc');

		$search = array(
						'keywords'  => $_POST['keywords'], 
						'star'      => $_POST['star'], 
						'end'       => $_POST['end'], 
						'shop_name' => $_POST['shop_name'],
						'city'      => $_POST['city'],
						'pageNum'   => $_POST['pageNum'],
						'buygroup'  => $_POST['buygroup'],
						'categroy'  => $_POST['categroy'],
						'zifenlei'  => $_POST['zifenlei'],
						'activity'	=> $_POST['activity'],
						'field'		=> $_POST['field'],
						// 'numPerPage' => $pages['numPerPage']
						);

		//特价区域商品id
		// $goodsid = M('activity')->field('');
		// if($pages[''])
		$this->assign('goods', $row);
		$this->assign('pages', $pages);
		$this->assign('search', $search);
		$this->display();
	}

	/**
	 * [分页数据]
	 * @Author   Axing
	 * @DateTime 2017-07-31
	 * @return   [type]     [description]
	 */
	public function page($currentPage, $numPerPage) {

		$currentPage = empty($currentPage) || is_null($currentPage)?1:$currentPage;
		
		$numPerPage = empty($numPerPage) || is_null($numPerPage)?100:$numPerPage;
		//多少条数据
		$pages['total'] = M('goods')->max("goodsid");
		$pages['rtotal'] = $pages['total']-($numPerPage*$currentPage);
		if($currentPage == 1) {
			$pages['ltotal'] = $pages['total'];
		} else {
			$pages['ltotal'] = $pages['total']-(($currentPage-1)*$numPerPage);
		}
		$pages['numPerPage'] = $numPerPage;
		$pages['currentPage'] = $currentPage;
		return $pages;
	}


	/**
	 * [处理商品审核]
	 * @Author   Axing
	 * @DateTime 2017-07-26
	 * @return   [type]     [description]
	 */
	public function check() {
		$goodsid = implode(',',$_POST['goodsid']);

		if($_POST['type'] == 0) {
			$data['check'] = 0;
		} else {
			$data['check'] = 1;
		}

		$result = M('Goods')->where('goodsid in ' . '(' . $goodsid . ')')->save($data);
		$this->ajaxReturn($result);
	}

	/**
	 * [商品添加页面]
	 * @Author   Axing
	 * @DateTime 2017-07-26
	 */
	public function add() {
		$data = $this->get_far_shop($row['muid'], $row['shopid']);
		$this->display();
	}

	/**
	 * [商品添加操作]
	 * @Author   Axing
	 * @DateTime 2017-07-27
	 * @return   [type]     [description]
	 */
	public function save() {

		$data = M('goods')->create();
		$data['images'] = $_POST['s'];
		$data['srcimages'] = $_POST['s'];
		$data['xiangQingTu'] = $_POST['s1'];
		
		$id = M('goods')->add($data);

		if($id > 0) {
			$res = $this->save_guige($id);
			if($res > 0) {
				echo '数据插入成功';
			}
		}
        $returnArr = array(
            "code"=>200,
            "callbackType"=>"closeCurrent",
            "navTabId"=>"fare_list",
            "forwardUrl"=>"index.php?c=Goods&a=index",
            "msg"=>"插入成功"
        );
        $this->ajaxReturn($returnArr);
	}

	/**
	 * [商品修改]
	 * @Author   Hybrid
	 * @DateTime 2017-08-01
	 * @return   [type]     [description]
	 */
	public function update() {
		$goods = M("goods"); // 实例化User对象
		// 要修改的数据对象属性赋值
		$data = $goods->create();
		$data['images'] = $_POST['s'];
		$data['srcimages'] = $_POST['s'];
		$data['xiangQingTu'] = $_POST['s1'];
		$result = $goods->save($data);

		$this->update_guige($_POST['guige'], $_POST['goodsid']);

        $returnArr = array(
            "statusCode"=>200,
            "callbackType"=>"closeCurrent",
            "navTabId"=>"fare_list",
            "forwardUrl"=>"index.php?c=Goods&a=index",
            "message"=>"插入成功",
            "rel"=>"12"
        );
// {"statusCode":"200", "message":"操作成功", "navTabId":"navNewsLi", "forwardUrl":"", "callbackType":"closeCurrent", "rel"."xxxId"}
        echo json_encode($returnArr);
	}

	/**
	 * [商品规格添加操作]
	 * @Author   Axing
	 * @DateTime 2017-07-27
	 * @return   [type]     [description]
	 */
	public function save_guige($id) {
		$data = $_POST['guige'];

		foreach($data as $k => $v) {
			$data[$k]['goodsid'] = $id;
		}
		$res = M('goodsselect')->addAll($data);
		// return $res;
	}

	/**
	 * [商品规格编辑操作]
	 * @Author   Hybrid
	 * @DateTime 2017-07-27
	 * @return   [type]     [description]
	 */
	public function update_guige($guige, $goodsid) {
		
		$goodsselect = M('goodsselect');
		$i = 0;
		unset($guige['fTitle']);
		foreach ($guige as $key => $value) {
			if($value['selectid'] != '') {
				$selectid .= $value['selectid'] . ',';
				$fTitle .= " WHEN " . $value['selectid'] . " THEN '" . $value['fTitle'] . "'";
				$sTitle .= " WHEN " . $value['selectid'] . " THEN '" . $value['sTitle'] . "'";
				$price .= " WHEN " . $value['selectid'] . " THEN " . $value['price'];
				$number .= " WHEN " . $value['selectid'] . " THEN " . $value['number'];
			} elseif ($value['selectid'] == '') {
				$add[$i]['fTitle'] = $value['fTitle'];
				$add[$i]['sTitle'] = $value['sTitle'];
				$add[$i]['price'] = $value['price'];
				$add[$i]['number'] = $value['number'];
				$add[$i]['goodsid'] = $goodsid;
				$i++;
			}
		}
		
		$selectid = rtrim($selectid, ",");
		$sql1 = "UPDATE goodsselect SET fTitle = CASE selectid ";
		$sql2 = " END,sTitle = CASE selectid ";
		$sql3 = " END,price = CASE selectid ";
		$sql4 = " END,number = CASE selectid ";
		$sql5 = " END WHERE selectid IN (" . $selectid . ")";

		$sql = $sql1 . $fTitle . $sql2 . $sTitle . $sql3 . $price . $sql4 . $number . $sql5;
		$result = $goodsselect->query($sql);
		
		$res = $goodsselect->addAll($add);
	}

	/**
	 * [规格数据获取]
	 * @Author   Axing
	 * @DateTime 2017-07-27
	 * @return   [type]     [description]
	 */
	public function get_guige() {
		$goodsselect = M('goodsselect');
		$guige_dad = $goodsselect->where('goodsid = ' . $_POST['goodsid'])->field('fTitle')->order('fTitle asc')->distinct(true)->select();
		$guige_son = $goodsselect->where('goodsid = ' . $_POST['goodsid'])->order('fTitle asc')->select();
		$this->ajaxReturn(array('guige_dad' => $guige_dad, 'guige_son' => $guige_son));
	}

	/**
	 * [删除规格]
	 * @Author   Axing
	 * @DateTime 2017-08-01
	 * @return   [type]     [description]
	 */
	public function del_guige() {
		$result = M('goodsselect')->where('selectid = ' . $_POST['selectid'])->delete();
	}

	/**
	 * [商品编辑操作]
	 * @Author   Axing
	 * @DateTime 2017-07-27
	 * @return   [type]     [description]
	 */
	public function edit() {
		$row = M('goods')->where('goodsid = ' . $_GET['uid'])->find();
		$zifenlei = M('zifenlei')->where('id = ' . $row['zixilie'])->field('id, name')->find();
		$row['zixilie'] = $zifenlei['id'];
		$row['name'] = $zifenlei['name'];
		$data = $this->get_far_shop($row['muid'], $row['shopid']);
		
		$this->assign('goods', $row);
		$this->display();

	}

	/**
	 * [厂家信息，运费模板]
	 * @Author   Axing
	 * @DateTime 2017-07-28
	 * @param    [type]     $faremlid [运费模板id]
	 * @param    [type]     $shopid   [厂商id]
	 * @return   [type]               [description]
	 */
	public function get_far_shop($faremlid,$shopid) {
		$fareml = M('fareml')->field('id, name')->select();

		if($shopid != '') {
			$moren_shopid = M('shop')->where('shopid = ' . $shopid)->field('name, shopid, zileimu')->find();
		}

		if($faremlid != '') {
			$faremlid = M('fareml')->where('id = ' . $faremlid)->field('id, name')->find();
		}

		$shop = M('shop')->field('shopid, name, zileimu')->select();
		if($moren_shopid['zileimu'] != '') {
			$ziid = $moren_shopid['zileimu'];
		} else {
			$ziid = $shop[0]['zileimu'];
		}

		$zileimu = M('zifenlei')->where('id in (' . $ziid . ')')->select();
		$this->assign('zileimu', $zileimu);
		$this->assign('moren_shopid', $moren_shopid);
		$this->assign('shop', $shop);
		$this->assign('fareml', $fareml);
		$this->assign('faremlid', $faremlid);
	}

	/**
	 * [子分类数据]
	 * @Author   Axing
	 * @DateTime 2017-07-31
	 * @return   [type]     [description]
	 */
	public function zifenlei() {
		$ziid = M('shop')->where('shopid = ' . $_POST['shopid'])->field('zileimu')->find();
		
		$row = M('zifenlei')->where('id in (' . $ziid['zileimu'] . ')')->select();

    	$data['fenleiid'] = I('post.fenleiid');
    	$row = D('Zifenlei')->ajax_index('id, name', $data);

    	// $this->ajaxReturn($row);
		$this->ajaxReturn($row);
	}

	//$array 要排序的数组
	//$row  排序依据列
	//$type 排序类型[asc or desc]
	//return 排好序的数组
	public function array_sort($array,$row,$type){
		  $array_temp = array();
		  foreach($array as $v){
		    $array_temp[$v[$row]] = $v;
		  }
		  if($type == 'asc'){
		    ksort($array_temp);
		  }elseif($type='desc'){
		    krsort($array_temp);
		  }else{
		  }
		  return $array_temp;
	}


	/**
	 * [删除商品功能]
	 * @Author   Axing
	 * @DateTime 2017-08-02
	 * @return   [type]     [description]
	 */
	public function del() {
		$goodsid = implode(',', I('goodsid'));
		$res = M('goods')->where('goodsid IN (' . $goodsid . ')')->delete();
		$res = M('goodsselect')->where('goodsid IN (' . $goodsid . ')')->delete();
        $returnArr = array(
            "code"=>200,
            "msg"=>"删除成功"
        );
        echo json_encode($returnArr);
	}

    public function uploadImg() {

        $upload = new \Think\Upload(); // 实例化上传类
        $upload->maxSize = 3145728; // 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
        $upload->rootPath = '../'; // 设置附件上传根目录
        $upload->savePath = 'srcimage/'; // 设置附件上传（子）目录
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功
            foreach ($info as $file) {
            	$this->ajaxReturn(array('type'=>$_POST['type'],'url'=>'../' . $file['savepath'] . $file['savename']));
                // print_r('../' . $file['savepath'] . $file['savename']);
            }
        }
    }

    /**
     * [图片上传插件删除功能]
     * @Author   Axing
     * @DateTime 2017-08-02
     * @return   [type]     [description]
     */
    public function del_img() {
        $src = substr($_POST['src'], 3);
        $this->ajaxReturn($src);
    }

    /**
     * [图片上传插件，编辑页面获取图片]
     * @Author   Axing
     * @DateTime 2017-08-02
     * @return   [type]     [description]
     */
    public function get_img() {
    	// $_POST['id'] = '135768';
    	$row = M('goods')->where('goodsid=' . $_POST['goodsid'])->field('images, xiangQingTu')->find();
    	$data['images'] = explode(',',$row['images']);
    	$data['xiangQingTu'] = explode(',',$row['xiangQingTu']);
    	foreach ($data['images'] as $k => $v) {
    		if($v == '') {
    			unset($data['images'][$k]);
    		}
    	}

    	foreach ($data['xiangQingTu'] as $k => $v) {
    		if($v == '') {
    			unset($data['xiangQingTu'][$k]);
    		}
    	}

    	$data['images'] = array_merge($data['images']);
    	$data['xiangQingTu'] = array_merge($data['xiangQingTu']);
    	// var_dump($xiangQingTu);die;

    	// if(empty($data['images'][0])) {
    	// 	unset($data['images']);
    	// }
    	// if(empty($data['xiangQingTu'][0])) {
    	// 	unset($data['xiangQingTu']);
    	// }
    	$this->ajaxReturn($data);
    }
    
    /**
     * [高级检索页面]
     * @Author   Axing
     * @DateTime 2017-08-02
     * @return   [type]     [description]
     */
    public function search() {
    	$shop = M('shop')->field('shopid, name')->select();
    	$city = M('city')->field('id, name')->select();
    	$buygroup = D('Buygroup')->ajax_index('buygroup_id, name');
    	$categroy = D('Categroy')->ajax_index('cateid, name');
    	$zifenlei = D('Zifenlei')->ajax_index('id, name');

    	$this->assign('categroy', $categroy);
    	$this->assign('zifenlei', $zifenlei);
    	$this->assign('buygroup', $buygroup);
    	$this->assign('shop', $shop);
    	$this->assign('city', $city);
    	$this->display();
    }

    /**
     * [高级检索的子分类数据]
     * @Author   Axing
     * @DateTime 2017-08-21
     * @return   [array]     [子分类数据]
     */
    public function s_zifenlei() {
    	$data['fenleiid'] = I('post.cateid');
    	if(!$data['fenleiid']) {
    		unset($data['fenleiid']);
    	}
    	$row = D('Zifenlei')->ajax_index('id, name', $data);
    	$this->ajaxReturn($row);
    }

    /**
     * [特价区域操作]
     * @Author   Axing
     * @DateTime 2017-08-08
     * @return   [type]     [description]
     */
    public function activity() {
    	$id = I('post.id');
    	$type = I('post.type');
    	$action = I('post.action');
    	$data[$action] = $type;
    	$result = M('goods')->where('goodsid = ' . $id)->save($data);

    	if($result) {
	    	if($type == 0) {
    			$type = $action!='xihuan'?2:1;
	    		$this->ajaxReturn(array(
								"msg"    => "off", 
								"type"	 => $type
								));
    		} else {
    			$this->ajaxReturn(array(
								"msg"    => "on", 
			    				));
    		}
    	} else {
    		$this->ajaxReturn(array("msg" => "false"));
    	}
    }

    /**
     * [选为特定商品]
     * @Author   Hybrid
     * @DateTime 2017-08-09
     * @return   [type]     [description]
     */
    public function specific() {
    	$data['goodsid']  = I('post.goodsid');
    	$data['type'] 	  = I('post.type');
    	$str	  = I('post.str');
    	$activity =	M('activity');
    	$goodsid = $activity->where('goodsid = ' . $data['goodsid'] . ' AND type = ' . $data['type'])->find();

    	if($goodsid) {
    		$result = $activity->delete($goodsid['act_id']);
    		if($result) {
    			$this->ajaxReturn(array("msg"=>"删除" . $str . "特定商品成功"));
    		}
    	} else {
		   	$num = $activity->where('type = ' . $data['type'])->count();
				if(intval($num) < 8 || $num == null) {
					$result = $activity->add($data);
					if($result) {
						$this->ajaxReturn(array("msg" => $str . "特定商品插入成功"));
					}
				} else {
					$this->ajaxReturn(array("msg" => $str . "特定商品已超过八条，请删除后再插入"));
				}
    	}
    }

    /**
     * [选为拼团专区商品]
     * @Author   Axing
     * @DateTime 2017-08-18
     * @return   [type]     [description]
     */
    public function group_buy() {
		$id     = I('post.goodsid');
		$data['istuangou'] = I('post.istuangou');;		
    	$data['buygroup_id'] = I('post.buygroup_id');
    	$result = M('goods')->where('goodsid = ' . $id)->save($data);
    	if($result) {
    		$this->ajaxReturn(array("msg" => true));
    	} else {
    		$this->ajaxReturn(array("msg" => false));
    	}
    }

    public function xiaoliang() {
    	$value = '111';
    }

    public function huanc() {
    	$value = S('name');
    	var_dump($value);die;
    }
}